package coml.allen.api.quickstart;

import com.rabbitmq.client.*;

/**
 * @author sesshomaru
 * @date 2020/11/12 22:40
 */
public class Consumer {
    public static void main(String[] args) throws Exception{
        ConnectionFactory connectionFactory = new ConnectionFactory();

        connectionFactory.setHost("192.168.1.102");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        /**
         * 声明队列
         * String queue,     队列名
         *
         * boolean durable,     是否持久化，重启也不会删除队列
         *
         * boolean exclusive,   是否时独占，如果是true就像顺序消费，这个队列只有能有一个连接可以监听，别的都不可以，
         *                      就像加了锁一样，保证了消息消费的 先进先出的顺序
         *
         * boolean autoDelete,  如果队列脱离了exchange就会自动删除
         *
         * Map<StringObject> arguments
         *
         */
        String queueName = "test001";
        channel.queueDeclare(queueName,true,false,false,null);

        // 创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        /**
         * 设置channel
         *String queue,  队列名
         * boolean autoAck,  是否自动签收
         * Consumer callback    设置消费者
         */
        channel.basicConsume(queueName,true,queueingConsumer);

        while (true) {
            // 获取消息 queueingConsumer.nextDelivery()获取一条消息
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("消费端: " + msg);
            //Envelope envelope = delivery.getEnvelope();

        }

    }
}
